package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.common.core.utils.DateUtils;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.*;
import com.yfp.operation.domain.vo.MiniBannerListVO;
import com.yfp.operation.domain.vo.MiniBannerVO;
import com.yfp.operation.enums.CouponStatus;
import com.yfp.operation.enums.MarketingEnums;
import com.yfp.operation.enums.MiniBannerPositionEnums;
import com.yfp.operation.mapper.*;
import com.yfp.operation.mapper.*;
import com.yfp.operation.service.MarCouponService;
import com.yfp.operation.service.MarketingService;
import com.yfp.operation.service.MiniBannerService;
import com.yfp.tissue.api.RemotePositionService;
import com.yfp.tissue.domain.Position;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @description 针对表【mini_banner(小程序banner)】的数据库操作Service实现
 * @createDate 2024-07-17 16:43:18
 */
@Service
@Slf4j
public class MiniBannerServiceImpl extends ServiceImpl<MiniBannerMapper, MiniBanner> implements MiniBannerService {

    @Resource
    private MarketingService marketingService;
    @Resource
    private MarCouponService marCouponService;

    @Autowired
    private MiniBannerMapper miniBannerMapper;
    @Resource
    private MarketingMapper marketingMapper;
    @Resource
    private MiniBannerPositionMapper miniBannerPositionMapper;
    @Resource
    private RemotePositionService remotePositionService;
    @Resource
    private LotteryRecordsMapper lotteryRecordsMapper;
    @Resource
    private ActivitySignInsMapper activitySignInsMapper;

    @Override
    public List<MiniBanner> getAllMiniBanners(String name, String cityName) {
        MiniBannerDTO miniBannerDTO = new MiniBannerDTO();
        miniBannerDTO.setCityName(cityName);
        miniBannerDTO.setName(name);
        List<MiniBanner> allMiniBanners = miniBannerMapper.selectAll(miniBannerDTO);
        return allMiniBanners;
    }

    /**
     * 获取小程序banner列表
     *
     * @param
     * @return
     */
    @Override
    public List<MiniBannerListVO> getMiniBannersList(String name, String cityName) {
        List<MiniBanner> allMiniBanners = getAllMiniBanners(name, cityName);
        Map<Integer, List<MiniBanner>> bannersByPosition = allMiniBanners.stream().collect(Collectors.groupingBy(MiniBanner::getPosition, Collectors.toList()));
        // 用来获取总数
        List<MiniBanner> allMiniBannersCount = getAllMiniBanners(null, cityName);
        Map<Integer, List<MiniBanner>> bannersCountByPosition = allMiniBannersCount.stream().collect(Collectors.groupingBy(MiniBanner::getPosition, Collectors.toList()));

        // 转换为 MiniBannerListVO
        List<MiniBannerListVO> miniBannerListVOS = bannersByPosition.entrySet().stream().map(entry -> {
            MiniBannerListVO miniBannerListVO = new MiniBannerListVO();
            miniBannerListVO.setPosition(entry.getKey());
            miniBannerListVO.setBanners(entry.getValue());
            List<MiniBanner> miniBanners = bannersCountByPosition.get(entry.getKey());
            miniBannerListVO.setCount(miniBanners.size());
            return miniBannerListVO;
        }).collect(Collectors.toList());

        return miniBannerListVOS;
    }

    /**
     * 获取小程序弹窗列表
     * @param miniBannersListDTO
     * @return
     */
    @Override
    public List<MiniBanner> getMiniBanner(MiniBannersListDTO miniBannersListDTO) {
        List<MiniBanner> list = miniBannerMapper.getMiniBanner(miniBannersListDTO);
        return list;
    }

    @Override
    public MiniBannerVO getMiniBannerById(Long id) {
        MiniBanner miniBanner = baseMapper.selectById(id);
        MiniBannerVO miniBannerVO = BeanUtil.toBean(miniBanner, MiniBannerVO.class);

        // 获取关联的 活动 or 券 or 礼包 名称
        String marketingName = marketingService.getNameById(miniBanner.getMarketingId());
        miniBannerVO.setMarketingName(marketingName);
        // 全部点位不查
        if (miniBanner.getPositionType() != null && miniBanner.getPositionType() != 1 && miniBanner.getPositionType() != 3) {
            // 获取关联的点位
            List<String> list = miniBannerPositionMapper.getByBannerId(id);
            if (!CollUtil.isEmpty(list)) {
                miniBannerVO.setPositionIds(list);
            }
        }

        return miniBannerVO;
    }

    @Override
    public void createMiniBanner(MiniBannerDTO miniBannerDTO) {
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        MiniBanner miniBanner = BeanUtil.toBean(miniBannerDTO, MiniBanner.class);
        miniBanner.setDeptId(deptId);
        // 校验活动是否失效
        Object marById = marketingService.getMarById(miniBanner.getMarketingId());
        this.checkMarStatus(marById, miniBannerDTO);
        // 创建弹窗banner 3
        this.createMiniBannerPopup(miniBanner);
        // 创建轮播图1、2、4
        this.createMiniBannerCarousel(miniBanner);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createMiniBannerPopup(MiniBanner miniBanner) {
        // 如果不是弹窗banner 3，则直接返回
        if (MiniBannerPositionEnums.HOME_PAGE_POPUP_BANNER.getCode() != miniBanner.getPosition()) {
            return;
        }

//        // 清空以前存在的弹窗，弹窗只能有一个
//        baseMapper.delete(Wrappers.lambdaQuery(MiniBanner.class)
//                .eq(MiniBanner::getPosition, MiniBannerPositionEnums.HOME_PAGE_POPUP_BANNER.getCode())
//                        .eq(MiniBanner::getCityName, miniBanner.getCityName())
//                );

        if (miniBanner.getPositionType() == 1 || miniBanner.getPositionType() == 3) {
            LambdaQueryWrapper<MiniBanner> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MiniBanner::getPosition, 3);
            wrapper.in(MiniBanner::getPositionType, 1, 3);
            wrapper.eq(MiniBanner::getCityName, miniBanner.getCityName());
            List<MiniBanner> list = baseMapper.selectList(wrapper);
            if (!CollUtil.isEmpty(list) && list.size() >= 3) {
                throw new ServiceException("最多只能添加3个全部点位的弹窗");
            }
        }



        // 重新设置对应的券 的弹窗
        if (Objects.isNull(miniBanner.getMarketingId())) {
            return;
        }

        Marketing marketing = marketingMapper.selectById(miniBanner.getMarketingId());
        if (MarketingEnums.COUPON.getType().equals(marketing.getType())) {
            Long marCouponId = marketingService.getIdById(miniBanner.getMarketingId());
            marCouponService.setMiniBannerPopup(marCouponId, miniBanner.getImg());
        }

        // 添加新的弹窗
        miniBanner.setCreateTime(DateUtils.getNowDate());
        miniBanner.setCreateUserId(SecurityUtils.getUserId());
        miniBanner.setUpdateTime(DateUtils.getNowDate());
        miniBanner.setUpdateUserId(SecurityUtils.getUserId());
        baseMapper.add(miniBanner);
        if (miniBanner.getPositionType() == 0) {
            List<Position> positions = remotePositionService.getPositionList(miniBanner.getCityName()).getData();
            if (!CollUtil.isEmpty(positions)) {
                List<String> positionIds = positions.stream().map(item -> item.getPositionId()).toList();
                miniBanner.setPositionIds(positionIds);
            }
        }
        if (!CollUtil.isEmpty(miniBanner.getPositionIds())) {
            // 批量添加
            miniBannerPositionMapper.adds(miniBanner.getPositionIds(), miniBanner.getId());
        }
    }

    @Override
    public void createMiniBannerCarousel(MiniBanner miniBanner) {
        // 创建轮播图1、2、4、5
        List<Integer> positions = ListUtil.of(MiniBannerPositionEnums.HOME_PAGE_BANNER.getCode()
                , MiniBannerPositionEnums.HOME_PAGE_BOTTOM_BANNER.getCode()
                , MiniBannerPositionEnums.EAT_PAGE_BANNER.getCode()
                , MiniBannerPositionEnums.MALL_BANNER.getCode());

        if (!positions.contains(miniBanner.getPosition())) {
            return;
        }

        // 添加新的轮播图
        miniBanner.setCreateTime(DateUtils.getNowDate());
        miniBanner.setCreateUserId(SecurityUtils.getUserId());
        miniBanner.setUpdateTime(DateUtils.getNowDate());
        miniBanner.setUpdateUserId(SecurityUtils.getUserId());
        baseMapper.insert(miniBanner);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMiniBanner(MiniBannerDTO miniBannerDTO) {
        MiniBanner miniBanner = BeanUtil.toBean(miniBannerDTO, MiniBanner.class);
        // 校验活动是否失效
        Object marById = marketingService.getMarById(miniBanner.getMarketingId());
        this.checkMarStatus(marById, miniBannerDTO);
        // 如果是弹窗banner 3
        if (MiniBannerPositionEnums.HOME_PAGE_POPUP_BANNER.getCode() == miniBanner.getPosition()) {
            if (Objects.nonNull(miniBannerDTO.getMarketingId())) {
                Marketing marketing = marketingService.getById(miniBannerDTO.getMarketingId());
                if (marketing.getType().equals(1)) {
                    marCouponService.updatePopupUrl(miniBanner.getImg(), marketing.getMarCouponId());
                }
            }
            if (!CollUtil.isEmpty(miniBannerDTO.getPositionIds())) {
                // 删除
                miniBannerPositionMapper.deleteByBannerId(miniBannerDTO.getId());
                // 批量添加
                miniBannerPositionMapper.adds(miniBannerDTO.getPositionIds(), miniBannerDTO.getId());
            }
        }

        miniBanner.setUpdateTime(DateUtils.getNowDate());
        miniBanner.setUpdateUserId(SecurityUtils.getUserId());
        baseMapper.updateById(miniBanner);
    }

    @Override
    public void deleteMiniBanner(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public MiniBanner findLastByMarketingId(Long marketingId) {
        return miniBannerMapper.findLastByMarketingId(marketingId);
    }

    @Override
    public boolean checkMiniBanner(String cityName) {
        return baseMapper.exists(Wrappers.lambdaQuery(MiniBanner.class).eq(MiniBanner::getPosition, 3).eq(MiniBanner::getCityName, cityName));
    }

    @Override
    public List<MarketingDTO> getMarketingList(MarketingNoActivityDTO activityDTO) {


        List<MarketingDTO> list = new ArrayList<>();

        // position1首页轮播2首页底部图3首页弹窗4吃饭轮播
        if (3 == activityDTO.getPosition()) {
            activityDTO.setBackgroundImg(false);
//            activityDTO.setStatus(1);
            list = marketingMapper.getAllMarketingNoActivity(activityDTO);

        } else {
            activityDTO.setBackgroundImg(true);
//            activityDTO.setStatus(1);
            list = marketingMapper.getAllMarketing(activityDTO);
        }

        // 抽奖
        if (activityDTO.getType() == null || activityDTO.getType() == 86) {
            List<MarketingDTO> marketingDTOS = lotteryRecordsMapper.activityList(activityDTO);
            if (!CollUtil.isEmpty(marketingDTOS)) {
                list.addAll(marketingDTOS);
            }
        }

        // 打卡
        if (activityDTO.getType() == null || activityDTO.getType() == 85) {
            List<MarketingDTO> marketingDTOS = activitySignInsMapper.activityList(activityDTO);
            if (!CollUtil.isEmpty(marketingDTOS)) {
                list.addAll(marketingDTOS);
            }
        }


        return list;
    }

    /**
     * 排序
     *
     * @param bannerSortDTO
     * @return
     */
    @Override
    public void sort(BannerSortDTO bannerSortDTO) {

        MiniBannersListDTO miniBanner = new MiniBannersListDTO();
        miniBanner.setPosition(bannerSortDTO.getPosition());
        miniBanner.setName(bannerSortDTO.getName());
        miniBanner.setCityName(bannerSortDTO.getCityName());
        List<MiniBanner> bannerList = miniBannerMapper.getMiniBanner(miniBanner);

        int i = bannerList.stream().filter(item -> item.getId().equals(bannerSortDTO.getMiniBannerId())).mapToInt(bannerList::indexOf).findFirst().orElse(-1);

        MiniBanner miniBanner1 = bannerList.get(i);
        MiniBanner miniBanner2 = new MiniBanner();
        Integer sort = miniBanner1.getSort();
        switch (bannerSortDTO.getDirection()) {
            case 1 :
                miniBanner2 = bannerList.get(i - 1);
                break;
            case 2 :
                miniBanner2 = bannerList.get(i + 1);
                break;
        }
        miniBanner1.setSort(miniBanner2.getSort());
        miniBanner2.setSort(sort);

        List<MiniBanner> list = new ArrayList<>();
        list.add(miniBanner1);
        list.add(miniBanner2);

        // 排序
        miniBannerMapper.sort(list);
    }

    @Override
    public void checkMarStatus(Object marById, MiniBannerDTO miniBannerDTO) {
        // 如果不是弹窗banner 3，则直接返回
        if (Objects.isNull(marById) &&  !miniBannerDTO.getPosition().equals(MiniBannerPositionEnums.HOME_PAGE_POPUP_BANNER.getCode())) {
            return;
        }

        if (Objects.isNull(marById)) {
            throw new ServiceException("活动不存在");
        }

        if (marById instanceof MarCoupon) {
            MarCoupon marCoupon = (MarCoupon) marById;
            if (!marCoupon.getStatus().equals(CouponStatus.ONE.getStatus()) && !marCoupon.getStatus().equals(CouponStatus.FOUR.getStatus())) {
                throw new ServiceException("活动已失效");
            }
        } else if (marById instanceof MarActivity) {
            MarActivity marActivity = (MarActivity) marById;
            if (!marActivity.getStatus().equals(CouponStatus.ONE.getStatus()) && !marActivity.getStatus().equals(CouponStatus.FOUR.getStatus())) {
                throw new ServiceException("活动已失效");
            }
        } else if (marById instanceof MarCouponPack) {
            MarCouponPack marCouponPack = (MarCouponPack) marById;
            if (!marCouponPack.getStatus().equals(CouponStatus.ONE.getStatus()) && !marCouponPack.getStatus().equals(CouponStatus.FOUR.getStatus())) {
                throw new ServiceException("活动已失效");
            }
        }
    }
}




